package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> rows = clazzMapper.list(clazzQueryParam);
        for(Clazz clazz: rows){
            if(clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开始");
            }else if(clazz.getEndDate().isAfter(LocalDate.now())){
                clazz.setStatus("进行中");
            }else {
                clazz.setStatus("已结束");
            }
        }
        Page<Clazz> p=(Page<Clazz>) rows;
        return new PageResult<Clazz>(p.getTotal(),p.getResult());
    }

    @Transactional
    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(Integer id) {
        // 检查该班级下是否有学生
        int studentCount = clazzMapper.countStudentsByClazzId(id);

        if (studentCount > 0) {
            // 抛出自定义异常
            throw new ClazzException("班级ID " + id + " 下还有学生，无法删除");
            // 或者自定义消息
            // throw new ClazzHasStudentsException("班级ID " + id + " 下还有 " + studentCount + " 名学生，无法删除");
        }

        // 如果没有学生，执行删除操作
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> finaAll() {
        return clazzMapper.findAll();
    }
}
